#include "dialog.h"
#include "ui_dialog.h"
#include"pricemap.h"
#include<QPushButton>
#include<QTextEdit>
#include<QLabel>
#include<QVBoxLayout>
#include<QVector>
#include<QPainter>

#include<QSpacerItem>

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
    resize(400, 800);

    label = new QLabel("\n    显示内容    \n");
    button  = new QPushButton("点击 搜索");
    textEdit = new QTextEdit();
    QVBoxLayout* layout = new QVBoxLayout(this);
    label->resize(300,30);

    button->setFixedSize(300, 90);  // 设置按钮的宽度为300，高度为90
    textEdit->setFixedSize(300,90);
    label->setStyleSheet("background-color: rgba(0, 0, 0, 0.7); color: white; border-radius: 5px; padding: 5px;");

    layout->addWidget(label);
    layout->addItem(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding));
    layout->addWidget(textEdit);
    layout->addItem(new QSpacerItem(2, 20, QSizePolicy::Minimum, QSizePolicy::Expanding));
    layout->addWidget(button);
    layout->setAlignment(Qt::AlignCenter);

    PriceMap();
    connect(button, &QPushButton::clicked, this, &Dialog::onButtonClick);

}

Dialog::~Dialog()
{
    delete ui;
}
void Dialog::paintEvent(QPaintEvent *event) {
    QDialog::paintEvent(event);

    // 创建 QPainter 对象，用于在对话框上绘制
    QPainter painter(this);

    // 加载背景图片
    QPixmap background(":/new/prefix1/backgroud.jpg");

    // 将背景图片缩放到对话框的大小
    background = background.scaled(size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

    // 绘制背景图片
    painter.drawPixmap(0, 0, background);
}

void Dialog::onButtonClick()
{
    if(bo)
    {
        bo = false;
        onButtonClick();
    }
    else bo = true;

    label->clear();
    QString text = textEdit->toPlainText();
    if(text.isEmpty())return;
    bool bo = PriceMap::m.contains(text);
    if(bo)
    {
        label->setText(text +"       "+PriceMap::m[text]);
    }
    QVector<QMap<QString,QString>::iterator> v = PriceMap::find(text);
    if(!v.isEmpty())
    {
        int n = 1;
        for(auto&x:v)
        {
            ++n;
            QString str = x.key() +"        "+ x.value()+'\n';
            QString curr = label->text();
            label->setText(curr+str);
        }
        label->setText("\n" + label->text());
        label->resize(300,30*n);
    }
    else
    {
        label->setText("\n没有找到这个东西\n");
    }

    textEdit->setReadOnly(false);  // 使 QTextEdit 可编辑
    textEdit->setFocus();
}

